package cn.jtfadmin.cms.service.impl;

import cn.jtfadmin.base.filesystem.config.FileSystem;
import cn.jtfadmin.base.lang.common.utils.RequestUtils;
import cn.jtfadmin.cms.domain.dto.CmsPageHeadDTO;
import cn.jtfadmin.cms.domain.dto.CmsPageMenuDTO;
import cn.jtfadmin.cms.domain.dto.CmsPageSysDTO;
import cn.jtfadmin.cms.domain.dto.CmsPageTopMenuDTO;
import cn.jtfadmin.cms.domain.entity.CmsEntity;
import cn.jtfadmin.cms.domain.entity.CmsMenuEntity;
import cn.jtfadmin.cms.service.CmsMenuService;
import cn.jtfadmin.cms.service.CmsPageService;
import cn.jtfadmin.cms.service.CmsService;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import java.awt.*;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CmsPageServiceImpl implements CmsPageService {

    @Autowired
    protected CmsService cmsService;

    @Autowired
    protected CmsMenuService cmsMenuService;

    @Autowired
    protected FileSystem fileSystem;

    public Map<String,Object> getInfo(String domain, String requestURI){
        List<CmsEntity> cmsEntities = cmsService.findByField("domain", domain);
        if(CollectionUtils.isEmpty(cmsEntities)){
            throw new IllegalArgumentException("域名未配置");
        }
        CmsEntity cms = cmsEntities.iterator().next();
        CmsPageHeadDTO head = new CmsPageHeadDTO(cms.getTitle(),cms.getKeywords(),cms.getDescription(), cms.getScriptAdd(), cms.getStyleAdd());
        CmsPageSysDTO sys = new CmsPageSysDTO(cms.getName(),
                fileSystem.getFileVisitHttpUrl(cms.getLogo()), cms.getRecordNum(),cms.getCopyright());
        List<String> banners = new ArrayList<>();
        List<CmsMenuEntity> menusEntities = cmsMenuService.findByField("cms.id", cms.getId());
        List<String> pageIndex = new ArrayList<>();
        if(!requestURI.equals(RequestUtils.getRequest().getContextPath()) && !requestURI.equals(RequestUtils.getRequest().getContextPath()+"/")){
            String indexStr  = requestURI.substring((RequestUtils.getRequest().getContextPath()+"/cms/page").length());
            String[] indexArray = StringUtils.delimitedListToStringArray(indexStr, "/");
            for (String index : indexArray) {
                if(StringUtils.hasText(index)){
                    pageIndex.add(index);
                }
            }
        }

        List<CmsMenuEntity> topMenus = menusEntities.stream().filter(t -> !StringUtils.hasText(t.getParentId())).sorted().collect(Collectors.toList());
        List<CmsPageTopMenuDTO> menus = new ArrayList<>(topMenus.size());
        for (int i = 0; i < topMenus.size(); i++) {
            CmsMenuEntity e = topMenus.get(i);
            CmsPageTopMenuDTO t = new CmsPageTopMenuDTO();
            t.setId(e.getId());
            t.setName(e.getName());
            t.setUrl(StringUtils.hasText(e.getUrl())? e.getUrl():"/cms/page/"+i);
            t.setContentHtml(e.getContentHtml());
            t.setCreateDateTime(e.getCreateDateTime());
            t.setLogo(fileSystem.getFileVisitHttpUrl(e.getLogo()));
            boolean current = false;
            if(pageIndex.size()>0){
                current = Integer.valueOf(pageIndex.get(0)).equals(i);
            }else {
                current = i==0;
            }
            if(current){
                String b = e.getBanners();
                if(StringUtils.hasText(b)){
                    String[] strings = StringUtils.delimitedListToStringArray(b, ",");
                    for (String string : strings) {
                        if(StringUtils.hasText(string)){
                            banners.add(fileSystem.getFileVisitHttpUrl(string));
                        }
                    }
                }
            }
            t.setCurrent(current);
            t.setShowChildrenMenu(Boolean.TRUE.equals(e.getShowChildrenMenu()));
            menus.add(t);
            fillChildrenMenu(t, menusEntities, pageIndex,1);
        }
        Map<String,Object> map = new HashedMap();
        map.put("head", head);
        map.put("sys", sys);
        map.put("menus", menus);
        if(!CollectionUtils.isEmpty(banners)){
            map.put("banners", banners);
        }
        String content = "";
        String contentId = "";
        List<List<? extends CmsPageMenuDTO>> menuListList = new ArrayList<>();
        List<? extends CmsPageMenuDTO> m = menus;
        while (m!=null){
            menuListList.add(m);
            List<? extends CmsPageMenuDTO> m1 = null;
            for (CmsPageMenuDTO menu : m) {
                if(menu.isCurrent()){
                    content = menu.getContentHtml();
                    contentId=menu.getId();
                    m1 = menu.getChildren();
                    break;
                }
            }
            m = m1;
        }

        if(Objects.nonNull(menuListList)){
            map.put("menuListList", menuListList);
        }
        map.put("content", content);
        map.put("contentUrl","/cms/menu/content/"+contentId+"?version="+ LocalDateTime.now().toEpochSecond(ZoneOffset.UTC));

        return map;
    }
    public void fillChildrenMenu(CmsPageMenuDTO parent, List<CmsMenuEntity> menusEntities, List<String> pageIndex, int index){
        List<CmsMenuEntity> topMenus = menusEntities.stream().filter(t -> Objects.equals(t.getParentId(), parent.getId())).sorted().collect(Collectors.toList());
        List<CmsPageMenuDTO> menus = new ArrayList<>(topMenus.size());
        for (int i = 0; i < topMenus.size(); i++) {
            CmsMenuEntity e = topMenus.get(i);
            CmsPageMenuDTO t = new CmsPageTopMenuDTO();
            t.setId(e.getId());
            t.setName(e.getName());
            t.setUrl(StringUtils.hasText(e.getUrl())? e.getUrl():parent.getUrl()+"/"+i);
            t.setContentHtml(e.getContentHtml());
            t.setCreateDateTime(e.getCreateDateTime());
            t.setLogo(fileSystem.getFileVisitHttpUrl(e.getLogo()));
            boolean current = false;
            if(pageIndex.size()>index){
                current = Integer.valueOf(pageIndex.get(index)).equals(i);
            }else {
                current = i==0;
            }
            t.setCurrent(current);
            fillChildrenMenu(t, menusEntities, pageIndex, index+1);
            menus.add(t);
        }
        if(!CollectionUtils.isEmpty(menus)){
            parent.setChildren(menus);
        }


    }

    @Override
    public ModelAndView page(String serverName, String requestURI) {
        ModelAndView modelAndView = new ModelAndView("default/index");
        modelAndView.addAllObjects(getInfo(serverName, requestURI));
        return modelAndView;
    }
}
